import csv
import json
import os
import traceback

from openpyxl import Workbook

from movie_spider.exceptions import EmptyFileName


class SaveFile:
    """
    该类将用来导出数据到不同的数据格式
    其他类可以通过继承的方法实现其方法
    """
    
    def __init__(self, movie_list):
        self._movie_list = movie_list
        self.movies_list = []

    @property
    def movies_with_dlinks(self):
        if not self.movies_list:
            for movie in self._movie_list:
                movie.download_links
                self.movies_list.append(
                    movie
                )
            return self.movies_list
        else:
            return self.movies_list

    def _get_fullpath(self, file_name, path):
        file_path = ""

        if not path:
            file_path = os.path.join(os.getcwd(), file_name)
        else:
            if not os.path.exists(path):
                os.mkdir(path)
            file_path = os.path.join(path, file_name)

        return file_path
        

    def to_excel(self, file_name, path=None):
        if not file_name:
            raise EmptyFileName("文件名不能为空")

        file_path = self._get_fullpath(file_name, path)
        
        if "xlsx" not in file_path:
            file_path = file_path + ".xlsx"

        
        try:
            max_link_length = max([len(m['download_links']) for m in self.movies_with_dlinks])
            
            wb = Workbook()
            sheet = wb.active
            sheet.cell(row=1, column=1, value="电影名")
            for l in range(max_link_length):
                sheet.cell(row=1, column=2 + l, value=f"下载链接{l+1}")

            for i, movie in enumerate(self.movies_list,2):
                sheet.cell(row=i, column=1, value=movie.title)
                for m, links in enumerate(movie.download_links,2):
                    sheet.cell(row=i, column=m, value=movie.download_links[m-2])

            wb.save(file_path)
            return file_path

        except Exception as e:
            print(f"调用函数 {__class__.__name__}.to_excel 出错了：{traceback.format_exc()}")


    def to_json(self, file_name, path=None):
        if not file_name:
            raise EmptyFileName("文件名不能为空")

        file_path = self._get_fullpath(file_name, path)

        if "json" not in file_path:
            file_path = file_path + ".json"

        try:
            with open(file_path,"w",encoding="utf-8") as fp:
                
                json.dump(
                    [dict(name=m.title,download_links=m.download_links) for m in self.movies_with_dlinks], 
                    fp
                    )
            
            return file_path

        except Exception as e:
            print(f"调用函数 {__class__.__name__}.to_json 出错了：{traceback.format_exc()}")

